package org.soar.helper;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.DisplayMetrics;

import com.google.inject.Inject;
import com.google.inject.Injector;
import org.soar.ActivityContext;
import org.soar.SoarApplication;
import org.soar.SoarContainer;
import org.soar.views.SoarDialog;
import org.soar.views.annotation.ViewById;
import org.soar.views.uicomponent.SoarUIComponent;

public class SoarHelper {
	
	@Inject
	private ActivityContext ac;
	
	public float getDensity() {
		Context context = ac.getActivity();
		Resources resources = context.getResources();
		DisplayMetrics dm = resources.getDisplayMetrics();
		return dm.density;
	}
	
	public static void processOnCreateActivity(Context context) {
		Injector injector = ((SoarApplication)context.getApplicationContext()).getInjector();
		SoarContainer soar = ((SoarApplication)context.getApplicationContext()).getSoarContainer();
		soar.processActivityContext((Activity) context);
		
		injector.injectMembers(context);
	}
	
	public static Map getMapFromExtra(Bundle extra) {
		if(extra != null){
			Map map = new HashMap();
			for(String key : extra.keySet()){
				map.put(key, extra.getSerializable(key));
			}
			return map;
		}
		return null;
	}
	
	public void renderMembersWithAnnotationForUIComponent(SoarUIComponent uicomponent){
		renderMembersWithViewById(uicomponent);
	}
	
	public void renderMembersWithAnnotationForDialog(SoarDialog dialog){
		renderMembersWithViewById(dialog);
	}
	
	private void renderMembersWithViewById(Object o){
		Class cls = o.getClass();
		Class targetClass = o instanceof SoarDialog ? SoarDialog.class : SoarUIComponent.class; 

        while (cls != targetClass) {
        	
        	Field[] fields = cls.getDeclaredFields();
    		for(int i = 0; i < fields.length; i++){
    			Field field = fields[i];
    			ViewById anno =  field.getAnnotation(ViewById.class);
    			if ( anno != null){
    				try {
    					int id = anno.id();
    					//TODO: make id default with the field name
    					field.setAccessible(true);
    					if(targetClass == SoarDialog.class){
    						field.set(o, ((SoarDialog) o).findViewById(id));
    					}else{
    						field.set(o, (((SoarUIComponent) o).getView()).findViewById(id));
    					}
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		}
        	
            cls = cls.getSuperclass();
        }
		
	}
	
	
}
